import django_filters
from django.db.models import Q

from rest_framework import pagination

from record.models import Car, Record


def normalize(carno):
    """规范化车牌号"""
    return carno.replace(' ', '').upper()


class CustomPagination(pagination.PageNumberPagination):
    """自定义分页"""
    page_size_query_param = 'size'
    max_page_size = 50


class RecordFilterSet(django_filters.FilterSet):
    carno = django_filters.CharFilter(method='filter_by_carno', label='请输入车牌号或车主姓名')
    min_date = django_filters.DateTimeFilter(field_name='makedate', lookup_expr='gte')
    max_date = django_filters.DateTimeFilter(field_name='makedate', lookup_expr='lte')

    @staticmethod
    def filter_by_carno(queryset, name, value):
        value = normalize(value)
        return queryset.filter(Q(car__carno=value) |
                               Q(car__owner__contains=value))

    class Meta:
        model = Record
        fields = ('carno', 'min_date', 'max_date')


class CarFilterSet(django_filters.FilterSet):
    """自定义过滤"""
    carno = django_filters.CharFilter()
    owner = django_filters.CharFilter(lookup_expr='contains')

    class Meta:
        model = Car
        fields = ('carno', 'owner')
